package chd.edu.spzx.user.service.impl;

import chd.edu.spzx.user.service.SmsService;
import chd.edu.spzx.utils.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Zhang Chaoliang
 * create 2023
 */

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @Override
    public void sendCode(String phone) {

        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.hasText(code)){
            return;
        }

        //1. 生成验证码
        code  = RandomStringUtils.randomNumeric(4);

        //2. 把生成的验证码放到redis里面，设置过期时间
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        //3. 向手机号发送短信验证码
        sendMessage(phone,code);
    }

    /**
     * 向手机号发送短信验证码
     * @param phone
     * @param code
     */
    private void sendMessage(String phone, String code) {
        String host = "https://dfsmsv2.market.alicloudapi.com";
        String path = "/data/send_sms_v2";
        String method = "POST";
        String appcode = "0689cefcbe6941408b4bbad774b3c860";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content", "code:"+code);
        bodys.put("template_id", "TPL_0000");
        bodys.put("phone_number", phone);


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
